<?php

class Zen_Controller_Plugin_ErrorHandler extends Zend_Controller_Plugin_ErrorHandler
{
	/**
     * Const - Site is unavailable temporary
     */
	const EXCEPTION_TEMPORARY_UNAVAILABLE = 'EXCEPTION_TEMPORARY_UNAVAILABLE';
    
	public function preDispatch(Zend_Controller_Request_Abstract $request){


		if ( $request->getControllerName () == "error" ) return ;
		$cfg = Zend_Registry::get ( 'cnf' );
		$status503 = $cfg->status503;

		if ( !$status503) return ;
		$url = $_SERVER ['REQUEST_URI'];

		if (( preg_match ( '/^\/backend/', $url )) || 
			( preg_match ( '/^\/admin/', $url )) || 
			( preg_match ( '/^\/login/', $url )) || 
			( preg_match ( '/^\/logout/', $url )) || 
			( preg_match ( '/^\/profile/', $url ))) return;

		
		if(Zen_User::isLoged()) {
			$user=Zen_User::getOne(Zen_User::getId());
			$acl=Zend_Registry::get('acl');
			$resource='view_while_503';
			$role=$user['role'];
			if ($acl->has ( $resource )) {
				if ($acl->isAllowed ( $role, $resource, null )) {
					return;	
				}
			}
		}
			
		$error            = new ArrayObject(array(), ArrayObject::ARRAY_AS_PROPS);
		$exception = new Zen_Exception_Code503();
		$exceptionType    = get_class($exception);
		$error->exception = $exception;
		$error->request = clone $request;
		$error->type = self::EXCEPTION_TEMPORARY_UNAVAILABLE;
		$request->setParam('error_handler', $error)
			->setModuleName('pages')
			->setControllerName('error')
			->setActionName('error')
			->setDispatched(false);
	}
	
}
